package com.stonedt.spider.util;

import com.microsoft.playwright.*;
import org.springframework.stereotype.Component;

/**
 * Playwright工具类
 */
@Component
public class PlaywrightUtil {

    // Shared between all tests in this class.
    static Playwright playwright;
    static Browser browser;

    // New instance for each test method.
    static BrowserContext context;
    static Page page;

    // @PostConstruct
    public static void init() {
        try {
            System.out.println("初始化Playwright");
            playwright = Playwright.create();
            // 创建浏览器
            browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            context = browser.newContext();
            page = context.newPage();
//            // 打开浏览器，默认百度页面，不关闭
//            String url = "https://weixin.sogou.com/";
//            page.navigate(url);
            System.out.println("Playwright初始化完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void closeBrowser() {
        try {
            if (browser != null) {
                browser.close();
            }
            if (playwright != null) {
                playwright.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定页面的Html
     *
     * @param url 网页地址
     * @return String
     */
    public static String getHtml(String url) {
        long start = System.currentTimeMillis();
        try {
            if (playwright == null || browser == null) {
                init();
            }
            page = context.newPage();
            // 访问url,加500毫秒延迟，防止被封
            Thread.sleep(500);
            page.setDefaultNavigationTimeout(60000);
            page.setDefaultTimeout(60000);
            page.navigate(url);
            page.waitForLoadState();
            Thread.sleep(500);
            page.mouse().wheel(0, 5000);
            Thread.sleep(2000);
//            page.fill("");
            // 去掉HTML中的注释
            String content = page.content().replaceAll("<!--.*?-->", "");
            long end = System.currentTimeMillis();
            System.out.println("=================== playwright请求时间：" + (end - start) + "ms =====================");
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
//            page.close();
        }
    }

    /**
     * 返回页面 指定点击事件 跳转的新页面的url
     *
     * @param url
     * @param selector 指定点击事件的selector
     * @return String
     */
    public static String clickSelectorUrl(String url, String selector) {
        // return "";
        // 延迟500ms，防止访问失败
        try {
            Thread.sleep(200);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String result = "";
        try {
            if (playwright == null || browser == null) {
                init();
            }
            page = context.newPage();
            // 访问url
            page.setDefaultTimeout(10000);
            page.navigate(url);
            page.waitForLoadState();

            Page page1 = page.waitForPopup(() -> {
                // page.isChecked(selector);
                // 超过3秒则判定为无效url
                page.setDefaultTimeout(3000);
                page.click(selector);
            });
            result = page1.url();
            page1.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String url = "http://chinanev.net/news/index.html";
        String html = getHtml(url);
        System.out.println("title = " + html);
       /* Document document = Jsoup.parse(html);
        List<String> list = document.select("a[data-spm=\"d_title\"]").eachText();
        for (String title : list) {
            System.out.println("title = " + title);
        }*/
        
    }

}
